package com.cp.weixin.util;

import org.apache.commons.lang3.StringUtils;

public class CharacterUtil {
    /**
     * 字符串转16进制内码
     * @param str ab一2𫠂仯3𫠯4
     * @return \\u61\\u62\\u4e00\\u32\\u2b802\\u4eef\\u33\\u2b82f\\u34\\u34
     */
    public static String stringToCodePoints(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        str.codePoints().forEach(cp -> stringBuilder.append("\\u").append(Integer.toHexString(cp)));
        return stringBuilder.toString();
    }

    /**
     * 内码转汉字
     * @param codePoints \\u61\\u62\\u4e00\\u32\\u2b802\\u4eef\\u33\\u2b82f\\u34\\u34
     * @return ab一2𫠂仯3𫠯4
     */
    public static String codePointsToString(String codePoints) {
        StringBuilder stringBuilder = new StringBuilder();
        for(String hexCodePoint : codePoints.split("\\\\u")){
            if(StringUtils.isNotBlank(hexCodePoint)) {
                stringBuilder.append(codePointToString(Integer.parseInt(hexCodePoint, 16)));
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 十进制转汉字
     * @param cp code point 汉字内码
     * @return
     */
    public static String codePointToString(int cp) {
        StringBuilder sb = new StringBuilder();
        if (Character.isBmpCodePoint(cp)) {
            sb.append((char) cp);
        } else if (Character.isValidCodePoint(cp)) {
            sb.append(Character.highSurrogate(cp));
            sb.append(Character.lowSurrogate(cp));
        } else {
            sb.append('?');
        }
        return sb.toString();
    }

    /**
     * 获取字符串真实长度
     * @param str
     * @return
     */
    public static int length(String str) {
        return str.codePointCount(0, str.length());
    }
}
